import 'package:sleep/single/point_model.dart';

//5个点的峰值
class PeakFind {
  static List<WavePoint> findPeaks(List<double> data,
      {int halfwindowSize = 3, int startIndex = 0}) {
    List<WavePoint> peaksAndValleys = [];
    List<double> windowData = [];

    final windowSize = halfwindowSize * 2 + 1;
    for (int i = 0; i < data.length; i++) {
      windowData.add(data[i]);
      if (windowData.length > windowSize) {
        windowData.removeAt(0); // 移除窗口最旧的数据点
      }

      if (windowData.length == windowSize) {
        int bigCount = 0;
        int smallCount = 0;
        int equalCount = 0;
        final currentIndex = i - halfwindowSize;
        final centerValue = data[currentIndex];

        for (int j = 0; j < windowSize; j++) {
          final jIndex = j + i - halfwindowSize * 2;
          final jcurent = data[jIndex];

          if (currentIndex == jIndex) continue;

          if (centerValue > jcurent) {
            bigCount += 1;
          } else if (centerValue < jcurent) {
            smallCount += 1;
          } else {
            equalCount += 1;
          }

          if (bigCount > 0 && smallCount > 0) break;
          if (equalCount > 0) break;
        }

        if (smallCount == 0 && equalCount == 0) {
          //最大值
          peaksAndValleys.add(WavePoint(
              (currentIndex + startIndex).toDouble(), data[currentIndex],
              type: WaveType.peak));
        }

        if (bigCount == 0 && equalCount == 0) {
          //最小值
          peaksAndValleys.add(WavePoint(
              (currentIndex + startIndex).toDouble(), data[currentIndex],
              type: WaveType.valley));
        }
      }
    }

    return peaksAndValleys;
  }
}
